<?php

namespace App\Http\Controllers\Auth;

use App\Repositories\UsersRepository;
use App\Repositories\UsersRolesRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Exception;
use Log;

/**
 *  集中认证
 */
class IndexController extends Controller
{
    private $UsersRepository=null;
    private $UsersRolesRepository=null;
    public function __construct(
        UsersRepository $UsersRepository,
        UsersRolesRepository $UsersRolesRepository
        )
    {
        $this->UsersRepository = $UsersRepository;
        $this->UsersRolesRepository=$UsersRolesRepository;
    }

    public function Login(Request $request, $usertype)
    {
         if (!env('APP_DEBUG') && 'members'!=$usertype) {
            $code =  trim($request->input('code'));
            $key = trim($request->input('key'));
            if (!captcha_api_check($code,$key))
            {
                return response()->json(['message' => '验证码错误', 'code' => 1]);
            }
         }

        $credentials = request(['accountname', 'password']);
        $credentials['Status'] = 0;
        if (!$token = auth($usertype)->attempt($credentials)) {
            return response()->json(['message' => '账号或密码错误', 'code' => 1]);
        }
        $userInfo = auth($usertype)->user();
        $userInfo->update([
            'LoginTime' => time(), 'LastIp' => $_SERVER["REMOTE_ADDR"], 'LoginCount' => $userInfo->LoginCount + 1
        ]);
        $res = $this->respondWithToken($token, $userInfo, $usertype);
        return $res;
    }

    public function respondWithToken($token, $userInfo, $usertype)
    {

        $Roles = [];

        if ($usertype == 'users') {
            $Roles = $this->UsersRolesRepository->GetByUsersID($userInfo->ID);
        }
        if ($usertype == 'members') {//处理会员头像
             $userInfo->Avatar=$userInfo->Avatar==''?$userInfo->Avatar:$this->ToImageURL('/avatar/members/'.$userInfo->Avatar);
        }
        if ($usertype == 'users') {//处理会员头像
             $userInfo->Avatar=$userInfo->Avatar==''?$userInfo->Avatar:$this->ToImageURL('/avatar/users/'.$userInfo->Avatar);
        }
        if ($usertype == 'enterprise') {//处理会员头像
             $userInfo->Avatar=$userInfo->Avatar==''?$userInfo->Avatar:$this->ToImageURL('/avatar/enterprise/'.$userInfo->Avatar);
        }
        return response()->json([
            'code' => 0,
            'result'=>[
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth($usertype)->factory()->getTTL() * 60,
            'userInfos' => $userInfo,
            'roles' => ['admin'],
            ],
        ]);
    }
}
